package cz.schovjan.mte_proj.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import cz.schovjan.mte_proj.Constant;
import cz.schovjan.mte_proj.R;
import cz.schovjan.mte_proj.activity.LyricActivity;
import cz.schovjan.mte_proj.dto.LyricResult;
import cz.schovjan.mte_proj.service.Searcher;
import cz.schovjan.mte_proj.service.SearcherImpl;
import cz.schovjan.mte_proj.task.DownloadLyricTask;
import cz.schovjan.mte_proj.task.SearchLyricTask;

public class SearchByTextFragment extends Fragment {

    /**
     * There must be default constructor, so passing data to instance we must solve some other way.
     */
    public SearchByTextFragment() {
	super();
    }


    /**
     * Factory for creating fragments from data
     * @param type data passed to fragment
     * @return
     */
    public static SearchByTextFragment createInstance() {
	SearchByTextFragment df = new SearchByTextFragment();
	return df;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View v = inflater.inflate(R.layout.fragment_search_by_text, container, false);
	final Activity a = this.getActivity();
	final SearchByTextFragment sbtf = this;
	final ListView lv = (ListView) v.findViewById(R.id.stLvData);
	lv.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
		// nacteni textu pisne
		LyricResult lr = ((LyricResult) lv.getItemAtPosition(position));
		DownloadLyricTask dlt = new DownloadLyricTask(sbtf);
		dlt.execute(lr);
	    }
	});
	Button b = (Button) v.findViewById(R.id.stBtSearch);
	b.setOnClickListener(new OnClickListener() {

	    @Override
	    public void onClick(View v) {
		// spustit vyhledavani
		EditText etText = (EditText) getActivity().findViewById(R.id.etText);
		String text = etText.getText().toString();
		if (text.isEmpty()) {
		    Toast.makeText(a, R.string.err_empty_text, Toast.LENGTH_SHORT).show();
		} else {
		    SearchLyricTask st = new SearchLyricTask(a, lv);
		    st.execute(text);
		}
	    }
	});
	return v;
    }


    /**
     * Vyhozeni aktivity se zobrazenym textem
     * @param lr
     */
    public void startLyricAktivity(LyricResult lr) {
	// vyhozeni okna s textem pisne
	Intent la = new Intent(getView().getContext(), LyricActivity.class);
	la.putExtra(Constant.LYRIC, lr);
	startActivity(la);
    }
}